package com.rf.richfitwheel.workflow.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.feignclient.FSysUserService;
import com.rf.richfitwheel.admin.sys.dao.SqlAdapterMapper;
import com.rf.richfitwheel.admin.sys.model.OrgVO;
import com.rf.richfitwheel.admin.sys.vo.UserVO;
import com.rf.richfitwheel.admin.utils.UserUtil;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.DateUtils;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.workflow.cmd.JumpTaskCmd;
import com.rf.richfitwheel.workflow.cmd.RollbackTaskCmd2;
import com.rf.richfitwheel.workflow.conf.WorkflowContants;
import com.rf.richfitwheel.workflow.contants.StationProcessContant;
import com.rf.richfitwheel.workflow.dao.*;
import com.rf.richfitwheel.workflow.entity.HistoryProcessVo;
import com.rf.richfitwheel.workflow.feignclient.SysOrgFeignService;
import com.rf.richfitwheel.workflow.model.*;
import com.rf.richfitwheel.workflow.service.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.StartEvent;
import org.activiti.engine.*;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.delegate.event.ActivitiEventType;
import org.activiti.engine.delegate.event.impl.ActivitiEventBuilder;
import org.activiti.engine.history.*;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.persistence.entity.CommentEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.HistoricProcessInstanceEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.IdentityLink;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 流程相关Service
 *
 * @author zml
 */
@Slf4j
@Service
public class WfProcessServiceImp implements WfProcessService {
    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected IdentityService identityService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    private FSysUserService fSysUserService;
    @Autowired
    protected WfProcessTaskService wfProcessTaskService;

    @Autowired
    protected WfAuthRuleService wfAuthRuleService;
    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    private WfCommonMapper wfCommonMapper;
    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;// 注入dao
    @Autowired
    private ModelService modelService;
    @Autowired
    private PortalTodoSync portalTodoSync;
    @Autowired
    private WfProcessTransferService wfProcessTransferService;
    
    @Autowired
    private WfStationProcessOrderMapper wfStationProcessOrderMapper;
    @Autowired
    private WfStationProcessMapper wfStationProcessMapper;
    @Autowired
    private SysOrgFeignService sysOrgFeignService;
    @Autowired
    private WfAuthRuleMapper wfAuthRuleMapper;
    
    @Autowired
    private WfStationProcessParPubMapper wfStationProcessParPubMapper;
    /**
     * 流程查询、分页
     *
     * @param params
     * @param user
     * @return
     */
    @Override
    public PageUtils queryProcessList(Map<String, Object> params, UserVO user) {
        int page = Integer.parseInt(params.get("page").toString());
        int limit = Integer.parseInt(params.get("limit").toString());
        String startUseName = params.get("startUseName") != null ? params.get("startUseName").toString() : "";
        String processName = params.get("processName") != null ? params.get("processName").toString() : "";
        String oper_time_start = params.get("oper_time_start") != null ? params.get("oper_time_start").toString() : "";
        String oper_time_end = params.get("oper_time_end") != null ? params.get("oper_time_end").toString() : "";
        String processState = params.get("processState") != null ? params.get("processState").toString() : "";
        String description = params.get("description") != null ? params.get("description").toString() : "";
        String moduleType = params.get("moduleType") != null ? params.get("moduleType").toString() : "";
        String approveNo = params.get("approveNo") != null ? params.get("approveNo").toString() : "";

        HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery();
        //query.processInstanceTenantId(user.getTenantId());
        if (!"".equals(startUseName)) {
            query.variableValueLike("startUserName", "%" + startUseName.trim() + "%");
        }

        if (!"".equals(processName)) {
//            query.processDefinitionName(processName.trim());
            query.processDefinitionNameLike("%" + processName.trim() + "%");
        }

        if (!"".equals(description)) {
            query.processInstanceNameLike("%" + description + "%");
        }
        if(!"".equals(moduleType)){
            if("capitalbudget".equals(moduleType)){
                moduleType = "capitalBudget";
            }
            query.variableValueLike("moduleType", "%" + moduleType + "%");
        }
        if(!"".equals(approveNo)){
            query.variableValueLike("approveNo", "%" + approveNo + "%");
        }
        try {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (!"".equals(oper_time_start)) {
                query.startedAfter(format.parse(oper_time_start + " 00:00:00"));
            }
            if (!"".equals(oper_time_end)) {
                query.startedBefore(format.parse(oper_time_end + " 23:59:59"));
            }
        } catch (Exception e) {
            throw new BusinessException("日期格式不对");
        }
        if (WorkflowContants.ProcessInstanceState.RUN.getValue().equals(processState)) {
            query.unfinished();
        } else if (WorkflowContants.ProcessInstanceState.END.getValue().equals(processState)) {
            query.finished();
            query.notDeleted();
        } else if (WorkflowContants.ProcessInstanceState.TERMINATED.getValue().equals(processState)) {
            query.deleted();
        }

        List<HistoricProcessInstance> list = query.secretLevel(user.getSecretLevel()).orderByProcessInstanceStartTime().desc().listPage((page - 1) * limit, limit);// 创建历史流程实例查询

        List<HistoryProcessVo> hpvList = new ArrayList<HistoryProcessVo>();
        for (HistoricProcessInstance hpi : list) {
            HistoryProcessVo historyProcessVo = new HistoryProcessVo((HistoricProcessInstanceEntity) hpi);
            List<HistoricVariableInstance> historicVariableInstances = historyService.createHistoricVariableInstanceQuery().processInstanceId(hpi.getId()).list();
            Map<String, Object> processVariables = new HashMap<>();
            for (HistoricVariableInstance hvi : historicVariableInstances) {
                processVariables.put(hvi.getVariableName(), hvi.getValue());
            }
            historyProcessVo.setProcessVariables(processVariables);
            historyProcessVo.setDescription(hpi.getName());
            if (historyProcessVo.getStartUserId() != null) {
                User assiginObjec = identityService.createUserQuery().userId(historyProcessVo.getStartUserId()).singleResult();
                if (assiginObjec != null) {
                    historyProcessVo.setStartUserName(assiginObjec.getLastName());
                }
            }
            hpvList.add(historyProcessVo);
        }
        int count = (int) query.count();
        PageUtils pageUtils = new PageUtils(hpvList, count);
        return pageUtils;
    }


    @Override
    public Map<String, Object> getProcessVariablesByProcessInstanceId(String processInstanceId) {
        Map<String, Object> variables = this.runtimeService.getVariables(processInstanceId);
        return variables;
    }


    @Override
    public void recordTransfer(Task nowTask, Map<String, Object> variables) {
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) this.repositoryService.getProcessDefinition(nowTask.getProcessDefinitionId());
        ActivityImpl nowActivity = processDefinitionEntity.findActivity(nowTask.getTaskDefinitionKey());
        String taskType = this.getTaskType(nowActivity);
        String executionId = nowTask.getExecutionId();
        String parentExecutionId = "";
        String parentParentExecutionId = "";
        String fromUser = nowTask.getAssignee();
        Execution execution = runtimeService.createExecutionQuery().executionId(executionId).singleResult();
        if (StringUtils.isNotBlank(execution.getParentId())) {
            parentExecutionId = execution.getParentId();
        }

        //判断是多人还是单人任务
        if ("userTask".equals(taskType)) {
            List<ActivityImpl> activities = this.findNextUserTaskActivitys(nowActivity, variables);
            wfProcessTransferService.insetProcessTransfer(nowTask, fromUser, executionId, parentExecutionId, parentParentExecutionId, activities);//插入节点流转记录
        } else if ("sequential".equals(taskType)) {
            //分配方案为多人任务-串行
            //todo
        } else if ("parallel".equals(taskType)) {
            //分配方案为多人任务-并行
            Execution parentExecution = runtimeService.createExecutionQuery().executionId(parentExecutionId).singleResult();
            parentParentExecutionId = parentExecution.getParentId();
            //todo
        }
    }

    @Override
    public List<ActivityImpl> findNextUserTaskActivitys(ActivityImpl nowActivityImpl, Map<String, Object> variables) {
        List<ActivityImpl> activities = new ArrayList<>();
        if (ObjectUtils.isEmpty(nowActivityImpl)) {
            return activities;
        }
        List<PvmTransition> pvmTransitionList = nowActivityImpl.getOutgoingTransitions();
        for (PvmTransition pvmTransition : pvmTransitionList) {
            ActivityImpl activity = (ActivityImpl) pvmTransition.getDestination();
            if ("exclusiveGateway".equals(nowActivityImpl.getProperty("type"))) {
                Object conStr = pvmTransition.getProperty("conditionText"); // 获取线路判断条件信息
                String ElStr = "";
                if (conStr != null) {// 有条件
                    ElStr = String.valueOf(conStr);
                    ElStr = ElStr.substring(2, ElStr.length() - 1);
                    try {
                        boolean stringToBoolean = stringToBoolean(ElStr, variables);
                        if (stringToBoolean) {
                            if ("userTask".equals(activity.getProperty("type"))) {//用户任务
                                activities.add(activity);
                            }
                        }
                    } catch (ScriptException e) {
                        continue;
                    }
                }
            } else {// 没有条件
                if ("userTask".equals(activity.getProperty("type"))) {//用户任务
                    activities.add(activity);
                } else if ("exclusiveGateway".equals(activity.getProperty("type"))) {//排它网关
                    // 如果排他网关只有一条线路信息
                    activities.addAll(findNextUserTaskActivitys(activity, variables));
                } else if ("inclusiveGateway".equals(activity.getProperty("type"))) {//包容网关
                    // 如果排他网关只有一条线路信息
                    activities.addAll(findNextUserTaskActivitys(activity, variables));
                } else if ("parallelGateway".equals(activity.getProperty("type"))) {//并行网关
                    activities.addAll(findNextUserTaskActivitys(activity, variables));
                } else if ("endEvent".equals(activity.getProperty("type"))) {
                    //activities.add(activity);
                }
            }
        }
        return activities;
    }

    public String getTaskType(ActivityImpl activity) {
        String taskType = activity.getProperty("type").toString();
        if (activity.getProperties().containsKey("multiInstance")) {
            taskType = activity.getProperty("multiInstance").toString();
        }
        return taskType;
    }

    @Override
    public Set<ActivityImpl> findPrevUserTaskActivitys(ActivityImpl nowActivityImpl) {
        Set<ActivityImpl> activities = new HashSet<>();
        List<PvmTransition> pvmTransitionList = nowActivityImpl.getIncomingTransitions();
        for (PvmTransition pvmTransition : pvmTransitionList) {
            ActivityImpl activity = (ActivityImpl) pvmTransition.getSource();
            if ("userTask".equals(activity.getProperty("type"))) {//用户任务
                activities.add(activity);
                activities.addAll(findPrevUserTaskActivitys(activity));
            } else if ("exclusiveGateway".equals(activity.getProperty("type"))) {//排它网关
                // 如果排他网关只有一条线路信息
                activities.addAll(findPrevUserTaskActivitys(activity));
            } else if ("inclusiveGateway".equals(activity.getProperty("type"))) {//包容网关
                // 如果排他网关只有一条线路信息
                activities.addAll(findPrevUserTaskActivitys(activity));
            } else if ("parallelGateway".equals(activity.getProperty("type"))) {//并行网关
                activities.addAll(findPrevUserTaskActivitys(activity));
            }
        }
        return activities;
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstanceById(String processInstanceId) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return historicProcessInstance;
    }

    @Override
    public HistoricProcessInstance getHistoricProcessInstanceByBusinessKey(String businessKey) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
        return historicProcessInstance;
    }

    @Override
    public ProcessInstance getProcessInstanceById(String processInstanceId) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        return processInstance;
    }

    @Override
    public ProcessInstance getProcessInstanceByBusinessKey(String businessKey) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
        return processInstance;
    }


    /**
     * 签收任务
     *
     * @param taskId
     * @param userId
     */
    @Override
    public void doClaim(String taskId, String userId) {
        Task taskOld = taskService.createTaskQuery().taskId(taskId).includeProcessVariables().singleResult();
        List<IdentityLink> listId = taskService.getIdentityLinksForTask(taskId);
        List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
        List<String> uList = new ArrayList<>();
        List<String> uListOld = new ArrayList<>();
        if(userId == null){
            //检入，删掉门户的当前处理人任务,换成岗位
            uList = fSysUserService.getUserListByStationIds(String.join(",", uGroup))
                    .stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            if(!UserUtil.getUser().getId().equals(taskOld.getAssignee())){
                throw new BusinessException("对不起，您没有此流程操作权限！");
            }
            uListOld.add(taskOld.getAssignee());
        }else{
            //检出，删掉之前的岗位,换成待办处理人
            uList.add(userId);
            uListOld = fSysUserService.getUserListByStationIds(String.join(",", uGroup))
                    .stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            //删掉当前这个处理人
            uListOld.removeIf(userId::equals);
        }
        this.identityService.setAuthenticatedUserId(userId);
        this.taskService.claim(taskId, userId);
        this.identityService.setAuthenticatedUserId("");
        /*//把数据同步给门户
//        portalTodoSync.todoSyncDelete(taskOld, uListOld, (String) taskOld.getProcessVariables().get("moduleType"));
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(taskOld.getProcessInstanceId()).singleResult();
        HistoricProcessInstance hisInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        List<TaskPortalTodoSync> taskListNew = new ArrayList<>();
        TaskPortalTodoSync taskPortalTodoSync = new TaskPortalTodoSync();
        taskPortalTodoSync.setTask(taskOld);
        taskPortalTodoSync.setReceiveUsers(uList);
        taskListNew.add(taskPortalTodoSync);
        portalTodoSync.runDeleteAndNew(processInstance, taskOld, uListOld, (String) taskOld.getProcessVariables().get("moduleType"), hisInstance.getStartUserId(), taskListNew);*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doBackward(String currentTaskId, String targetTaskId, String approveMessage) {
        HistoricTaskInstance targetTask = historyService.createHistoricTaskInstanceQuery().taskId(targetTaskId).singleResult();
        Map<String, Object> variables = targetTask.getProcessVariables();
        Task task = taskService.createTaskQuery().taskId(currentTaskId).singleResult();
        //this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd(currentTaskId, targetTask.getTaskDefinitionKey(), task.getAssignee(), variables, "doback", approveMessage, WorkflowContants.ProcessResult.BACK.getValue(), false));
        if(!UserUtil.getUser().getId().equals(task.getAssignee())){
            //如果当前审批人不是正在操作的用户，且操作用户在审批人列表中时先签出，否则报没权限
            List<IdentityLink> listId = taskService.getIdentityLinksForTask(task.getId());
            List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
            List<String> resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            if(resUser.contains(UserUtil.getUser().getId())){
                //先签出
                doClaim(task.getId(), UserUtil.getUser().getId());
            }else{
                throw new BusinessException("对不起，您没有此流程操作权限，如果是未签出任务请到业务系统首页待办任务处进行签出后再处理！");
            }
        }
        //退回的时候不需要知道审批人，会默认取上一次审批人
        variables.remove("approveUserId");
        runtimeService.removeVariable(targetTask.getProcessInstanceId(), "approveUserId");
        this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd2(wfProcessTransferService, currentTaskId, targetTask.getTaskDefinitionKey(), "doback", approveMessage, WorkflowContants.ProcessResult.BACK.getValue(), variables));
        /*//完成现待办，发送新待办
        List<String> receiveUsers = new ArrayList<>();
        receiveUsers.add(task.getAssignee());
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).includeProcessVariables().singleResult();
        portalTodoSync.todoSyncDone(task, receiveUsers, instance.getProcessVariables().get("moduleType").toString());
        List<Task> taskNews = taskService.createTaskQuery().processInstanceId(task.getProcessInstanceId()).list();
        List<TaskPortalTodoSync> taskListNew = new ArrayList<>();
        taskListNew = taskNews.stream().map(m -> {
            TaskPortalTodoSync taskPortalTodoSync = new TaskPortalTodoSync();
            taskPortalTodoSync.setTask(m);
            List<String> resUser = new ArrayList<>();
            if(m.getAssignee() != null){
                resUser.add(m.getAssignee());
            }else{
                List<IdentityLink> listId = taskService.getIdentityLinksForTask(m.getId());
                List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
                resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            }
            taskPortalTodoSync.setReceiveUsers(resUser);
            return taskPortalTodoSync;
        }).collect(Collectors.toList());
        portalTodoSync.todoSync(instance, instance.getProcessVariables().get("moduleType").toString(), UserUtil.getUser().getId(), taskListNew);*/
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doForward(String currentTaskId, String targetTaskId, String approveMessage) {
        HistoricTaskInstance targetTask = historyService.createHistoricTaskInstanceQuery().taskId(targetTaskId).singleResult();
        Map<String, Object> variables = targetTask.getProcessVariables();
        //this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd(currentTaskId, targetTask.getTaskDefinitionKey(), task.getAssignee(), variables, "doback", approveMessage, WorkflowContants.ProcessResult.BACK.getValue(), false));
        this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd2(wfProcessTransferService, currentTaskId, targetTask.getTaskDefinitionKey(), "doback", approveMessage, WorkflowContants.ProcessResult.AGREE.getValue(), variables));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doJump(Task task, String targetTaskDefKey, String approveMessage, Map<String, Object> variables) {
        //this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd2(wfProcessTransferService, currentTaskId, targetTaskDefKey, "complete", approveMessage, WorkflowContants.ProcessResult.AGREE.getValue(), variables));
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) this.repositoryService.getProcessDefinition(task.getProcessDefinitionId());
        ActivityImpl nowActivity = processDefinitionEntity.findActivity(task.getTaskDefinitionKey());
        ActivityImpl targetActivity = processDefinitionEntity.findActivity(targetTaskDefKey);
        this.processEngine.getManagementService().executeCommand(new JumpTaskCmd(wfProcessTransferService, task.getId(), task.getExecutionId(), nowActivity, targetActivity, approveMessage, WorkflowContants.ProcessResult.AGREE.getValue(), variables));
    }

    /**
     * 发起人撤回
     *
     * @param processInstanceId 流程实例id
     * @param user              操作用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void restartByCreater(String processInstanceId, UserVO user) {
        //todo 有待验证，时间太紧，代码太多不得已提交
        List<Task> oldTasks = this.taskService.createTaskQuery().processInstanceId(processInstanceId).includeProcessVariables().list();
        ActivityImpl firstUserTask = this.getFirstUserTask(oldTasks.get(0).getProcessDefinitionId());
        HistoricTaskInstance targetTask = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .taskDefinitionKey(firstUserTask.getId()).orderByHistoricTaskInstanceEndTime().desc().list().get(0);
        Map<String, Object> variables = targetTask.getProcessVariables();
        variables.put("approveUserId", targetTask.getAssignee());//被退回后的任务审批人
        variables.put("taskState", WorkflowContants.ProcessResult.RECALL.getValue());//
        /*List<String> receiveUsers = new ArrayList<>();
        if(oldTasks.get(0).getAssignee() == null){
            List<IdentityLink> listId = taskService.getIdentityLinksForTask(oldTasks.get(0).getId());
            List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
            receiveUsers = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
        }else{
            receiveUsers.add(oldTasks.get(0).getAssignee());
        }*/
//        this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd(oldTasks.get(0).getId(), targetTask.getTaskDefinitionKey(), user.getId(), variables, "restart", "发起人撤回", WorkflowContants.ProcessResult.RECALL.getValue(), false));
        this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd2(wfProcessTransferService, oldTasks.get(0).getId(), targetTask.getTaskDefinitionKey(), "restart", "发起人撤回", WorkflowContants.ProcessResult.RECALL.getValue(), variables));
        /*//删除现待办，发送新待办
        portalTodoSync.todoSyncDelete(oldTasks.get(0), receiveUsers, oldTasks.get(0).getProcessVariables().get("moduleType").toString());
        List<Task> taskNews = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        List<TaskPortalTodoSync> taskListNew = new ArrayList<>();
        taskListNew = taskNews.stream().map(m -> {
            TaskPortalTodoSync taskPortalTodoSync = new TaskPortalTodoSync();
            taskPortalTodoSync.setTask(m);
            List<String> resUser = new ArrayList<>();
            if(m.getAssignee() != null){
                resUser.add(m.getAssignee());
            }else{
                List<IdentityLink> listId = taskService.getIdentityLinksForTask(m.getId());
                List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
                resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            }
            taskPortalTodoSync.setReceiveUsers(resUser);
            return taskPortalTodoSync;
        }).collect(Collectors.toList());
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
        portalTodoSync.todoSync(instance, instance.getProcessVariables().get("moduleType").toString(), UserUtil.getUser().getId(), taskListNew);*/
    }

    /**
     * 参与人撤回流程
     *
     * @param params {'processId': 流程实例id,
     *               *  'recallNodeKey': 要撤回的节点key,
     *               *  'deleteReason': 撤回原因
     *               *  }
     * @param user
     * @param system
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recall(Map<String, Object> params, UserVO user, UserVO system) {
        //todo 有待验证，时间太紧，代码太多不得已提交
        String processInstanceId = params.get("processInstanceId") != null ? params.get("processInstanceId").toString() : "";
        String targetTaskId = params.get("targetTaskId") != null ? params.get("targetTaskId").toString() : "";
        String approveMessage = params.get("approveMessage") != null ? params.get("approveMessage").toString() : "";
        if (StringUtils.isBlank(processInstanceId) || StringUtils.isBlank(targetTaskId) || StringUtils.isBlank(approveMessage)) {
            throw new BusinessException("参数不正确");
        }
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().unfinished().processInstanceId(processInstanceId).singleResult();
        if (historicProcessInstance == null) {
            throw new BusinessException("流程已结束，无法撤回！");
        }
        List<Task> oldTasks = taskService.createTaskQuery().processInstanceId(processInstanceId).includeProcessVariables().list();
        /*List<String> receiveUsers = new ArrayList<>();
        if(oldTasks.get(0).getAssignee() == null){
            List<IdentityLink> listId = taskService.getIdentityLinksForTask(oldTasks.get(0).getId());
            List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
            receiveUsers = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
        }else{
            receiveUsers.add(oldTasks.get(0).getAssignee());
        }*/
        HistoricTaskInstance targetTask = historyService.createHistoricTaskInstanceQuery().taskId(targetTaskId).singleResult();
        Map<String, Object> variables = targetTask.getProcessVariables();
//        this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd(oldTasks.get(0).getId(), targetTask.getTaskDefinitionKey(), user.getId(), variables, "recall", approveMessage, WorkflowContants.ProcessResult.RECALL.getValue(), false));
        this.processEngine.getManagementService().executeCommand(new RollbackTaskCmd2(wfProcessTransferService, oldTasks.get(0).getId(), targetTask.getTaskDefinitionKey(), "recall", approveMessage, WorkflowContants.ProcessResult.RECALL.getValue(), variables));
        /*//删除现待办，发送新待办
        portalTodoSync.todoSyncDelete(oldTasks.get(0), receiveUsers, oldTasks.get(0).getProcessVariables().get("moduleType").toString());
        List<Task> taskNews = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        List<TaskPortalTodoSync> taskListNew = new ArrayList<>();
        taskListNew = taskNews.stream().map(m -> {
            TaskPortalTodoSync taskPortalTodoSync = new TaskPortalTodoSync();
            taskPortalTodoSync.setTask(m);
            List<String> resUser = new ArrayList<>();
            if(m.getAssignee() != null){
                resUser.add(m.getAssignee());
            }else{
                List<IdentityLink> listId = taskService.getIdentityLinksForTask(m.getId());
                List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
                resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            }
            taskPortalTodoSync.setReceiveUsers(resUser);
            return taskPortalTodoSync;
        }).collect(Collectors.toList());
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
        portalTodoSync.todoSync(instance, instance.getProcessVariables().get("moduleType").toString(), UserUtil.getUser().getId(), taskListNew);*/
    }

    @Override
    public String getApproveAdviceByTaskId(String taskId) {
        List<Comment> comments = taskService.getTaskComments(taskId, "comment");
        if (!comments.isEmpty()) {
            return comments.get(0).getFullMessage();
        }
        return "";
    }

    @Override
    public List<Map<String, Object>> getHistoryTaskByProcessInstanceId(String processInstanceId) {
        List<Map<String, Object>> taskList = new LinkedList<>();
        //改为直接查结束的任务，终止的任务已处理成与正常结束的一样的道理即把终止原因存入Comment
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).finished().orderByHistoricTaskInstanceEndTime().desc().list();
        //未结束的任务需要单独处理下审批人
        List<HistoricTaskInstance> listUnfinish = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).unfinished().orderByTaskCreateTime().desc().list();

        for (int i = 0; i < listUnfinish.size(); i++) {
            HistoricTaskInstance hai = listUnfinish.get(i);
            Map<String, Object> _map = new LinkedHashMap<>();
            //如果是多实例可能出现多任务情况（会签）
            //todo 暂时不考虑会签情况
            List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).executionId(hai.getExecutionId()).list();
//			System.out.println("办理人：" + hai.getAssignee());
            //改为候选人
            List<IdentityLink> identityLinkListAll = new ArrayList<>();
            for (Task task : tasks) {
                List<IdentityLink> identityLinkList = taskService.getIdentityLinksForTask(task.getId());
                identityLinkListAll.addAll(identityLinkList);
            }
            List<String> listUQ = new ArrayList<String>();
            List<String> listGQ = new ArrayList<String>();
            for (IdentityLink identityLink : identityLinkListAll) {
                if (identityLink.getUserId() != null) {
                    listUQ.add(identityLink.getUserId());
                }
                if(identityLink.getGroupId() != null){
                    listGQ.add(identityLink.getGroupId());
                }
            }

            StringBuffer inPram = new StringBuffer();
            for (String ss : listUQ) {
                inPram.append("'" + ss + "',");
            }
            StringBuffer inPramG = new StringBuffer();
            for (String ss : listGQ) {
                inPramG.append("'" + ss + "',");
            }
            String assignee = "";
            String assigneeName = "";
            String sqlUser = "";
            if (!listUQ.isEmpty() && !listGQ.isEmpty()){
                String inp = inPram.toString().substring(0, inPram.toString().length() - 1);
                String inpG = inPramG.toString().substring(0, inPramG.toString().length() - 1);
                sqlUser = "select ID_ as userId,FIRST_,LAST_ as username from ACT_ID_USER WHERE ID_ in(" + inp + ")"
                        + " UNION "
                        + "select au.ID_ as userId,au.FIRST_,au.LAST_ as username from ACT_ID_USER au, ACT_ID_MEMBERSHIP me WHERE au.ID_=me.USER_ID_ and me.GROUP_ID_ in(" + inpG + ")";
            }else if(!listUQ.isEmpty()){
                String inp = inPram.toString().substring(0, inPram.toString().length() - 1);
                sqlUser = "select ID_ as userId,FIRST_,LAST_ as username from ACT_ID_USER WHERE ID_ in(" + inp + ")";
            }else if(!listGQ.isEmpty()){
                String inpG = inPramG.toString().substring(0, inPramG.toString().length() - 1);
                sqlUser = "select au.ID_ as userId,au.FIRST_,au.LAST_ as username from ACT_ID_USER au, ACT_ID_MEMBERSHIP me WHERE au.ID_=me.USER_ID_ and me.GROUP_ID_ in(" + inpG + ")";
            }else{
                //
            }
            List<Map<String, Object>> assiginObjecs = sqlAdapterMapper.selectSQL(sqlUser);
            Iterator<Map<String, Object>> iterator = assiginObjecs.iterator();

            for (; iterator.hasNext(); ) {
                Map<String, Object> assiginObjec = iterator.next();
                if (iterator.hasNext()) {
                    assignee += assiginObjec.get("userId") + ",";
                    assigneeName += assiginObjec.get("username") + ",";
                } else {
                    assignee += assiginObjec.get("userId");
                    assigneeName += assiginObjec.get("username");
                }
            }

            if (assigneeName != null) {
                _map.put("assigneeName", assigneeName);
            }
            if (assignee != null) {
                _map.put("assignee", assignee);
            }
//            System.out.println("活动ID:" + hai.getId());
            _map.put("taskId", hai.getId());
            _map.put("taskDefKey", hai.getTaskDefinitionKey());
//            System.out.println("流程实例ID:" + hai.getProcessInstanceId());
            _map.put("processInstanceId", processInstanceId);
//            System.out.println("活动名称：" + hai.getName());
            _map.put("taskName", hai.getName());
//            System.out.println("开始时间：" + DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));
            _map.put("startTime", DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));

//            System.out.println("结束时间：" + hai.getEndTime());
            if (hai.getEndTime() != null) {
                _map.put("endTime", DateUtils.format(hai.getEndTime(), DateUtils.DATE_TIME_PATTERN));
                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSED.getValue());
            } else {

                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSING.getValue());

            }
            List<Comment> comments = taskService.getTaskComments(hai.getId());
            //处理意见
            for (Comment cmt : comments) {
                _map.put("description", cmt.getFullMessage());
            }

            //审批意见
            _map.put("aproveAdvice", hai.getDescription());
            taskList.add(_map);
        }

        for (int i = 0; i < list.size(); i++) {
            HistoricTaskInstance hai = list.get(i);
            Map<String, Object> _map = new LinkedHashMap<String, Object>();
            if (hai.getAssignee() == null || "".equals(hai.getAssignee())) {
                continue;
            }
            _map.put("assignee", hai.getAssignee());
// 			List<User> assiginObjecs = fSysUserAuthService.getUserByIds(Arrays.asList( hai.getAssignee().split(",")));
            StringBuffer inPram = new StringBuffer();
            for (String ss : Arrays.asList(hai.getAssignee().split(","))) {
                inPram.append("'" + ss + "',");
            }
            String inp = inPram.toString().substring(0, inPram.toString().length() - 1);
            String querySql = "select ID_ as userId,FIRST_,LAST_ as username from ACT_ID_USER WHERE ID_ in(" + inp + ")";
            List<Map<String, Object>> assiginObjecs = sqlAdapterMapper.selectSQL(querySql);
            String assigneeName = "";
            Iterator<Map<String, Object>> iterator = assiginObjecs.iterator();

            for (; iterator.hasNext(); ) {
                Map<String, Object> assiginObjec = iterator.next();
                if (iterator.hasNext()) {

                    assigneeName += assiginObjec.get("username") + ",";
                } else {
                    assigneeName += assiginObjec.get("username");
                }
            }

            if (assiginObjecs != null) {
                _map.put("assigneeName", assigneeName);
            }

//            System.out.println("活动ID:" + hai.getId());
            _map.put("taskId", hai.getId());
            _map.put("taskDefKey", hai.getTaskDefinitionKey());
//            System.out.println("流程实例ID:" + hai.getProcessInstanceId());
            _map.put("processInstanceId", hai.getProcessInstanceId());
//            System.out.println("活动名称：" + hai.getName());
            _map.put("taskName", hai.getName());
//            System.out.println("开始时间：" + DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));
            _map.put("startTime", DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));

//            System.out.println("结束时间：" + hai.getEndTime());
            if (hai.getEndTime() != null) {
                _map.put("endTime", DateUtils.format(hai.getEndTime(), DateUtils.DATE_TIME_PATTERN));
                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSED.getValue());
            } else {

                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSING.getValue());

            }
            List<Comment> comments = taskService.getTaskComments(hai.getId());
            //处理意见
            for (Comment cmt : comments) {
                // _map.put("description", ((CommentEntity)cmt).getMessage());
                //解决处理意见超长展示不全问题
                _map.put("description", cmt.getFullMessage());
            }

            //审批意见
            _map.put("aproveAdvice", hai.getDescription());
            taskList.add(_map);
        }

        return taskList;
    }

    @Override
    public List<Map<String, Object>> getHistoryTaskByBusinessKey(String businessKey) {
        List<Map<String, Object>> taskList = new LinkedList<Map<String, Object>>();
        //改为直接查结束的任务，终止的任务已处理成与正常结束的一样的道理即把终止原因存入Comment
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery()
                .processInstanceBusinessKey(businessKey).finished().orderByHistoricTaskInstanceEndTime()
                .desc().list();
        //未结束的任务需要单独处理下审批人
        List<HistoricTaskInstance> list_unfinish = historyService.createHistoricTaskInstanceQuery()
                .processInstanceBusinessKey(businessKey)
                .unfinished().orderByTaskCreateTime()
                .desc().list();

        for (int i = 0; i < list_unfinish.size(); i++) {
            HistoricTaskInstance hai = list_unfinish.get(i);

            List<Comment> comments = taskService.getTaskComments(hai.getId());
            Map<String, Object> _map = new LinkedHashMap<String, Object>();
            //如果是多实例可能出现多任务情况（会签）
            List<Task> tasks = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).list();
//			System.out.println("办理人：" + hai.getAssignee());
            //改为候选人
            List<IdentityLink> identityLinkListAll = new ArrayList<IdentityLink>();
            for (Task task : tasks) {
                //多实例情况下，tasks中所有的task_def_key一样，不一样则是并行节点
                if (!task.getTaskDefinitionKey().equals(hai.getTaskDefinitionKey())) {
                    continue;
                }
                List<IdentityLink> identityLinkList = taskService.getIdentityLinksForTask(task.getId());
                identityLinkListAll.addAll(identityLinkList);
            }
            List<String> listUQ = new ArrayList<String>();
            for (IdentityLink identityLink : identityLinkListAll) {
                if (identityLink.getUserId() != null) {
                    listUQ.add(identityLink.getUserId());
                }
            }
            String assignee = "";
            String assigneeName = "";
            if (!listUQ.isEmpty()) {
                StringBuffer inPram = new StringBuffer();
                for (String ss : listUQ) {
                    inPram.append("'" + ss + "',");
                }
                String inp = inPram.toString().substring(0, inPram.toString().length() - 1);
                String querySql = "select ID_ as userId,FIRST_,LAST_ as username from ACT_ID_USER WHERE ID_ in(" + inp + ")";
                List<Map<String, Object>> assiginObjecs = sqlAdapterMapper.selectSQL(querySql);
                Iterator<Map<String, Object>> iterator = assiginObjecs.iterator();

                for (; iterator.hasNext(); ) {
                    Map<String, Object> assiginObjec = iterator.next();
                    if (iterator.hasNext()) {
                        assignee += assiginObjec.get("userId") + ",";
                        assigneeName += assiginObjec.get("username") + ",";
                    } else {
                        assignee += assiginObjec.get("userId");
                        assigneeName += assiginObjec.get("username");
                    }
                }
            }


            if (assigneeName != null) {
                _map.put("assigneeName", assigneeName);
            }
            if (assignee != null) {
                _map.put("assignee", assignee);
            }
//            System.out.println("活动ID:" + hai.getId());
            _map.put("actId", hai.getId());
            _map.put("activityDfId", hai.getTaskDefinitionKey());
//            System.out.println("流程实例ID:" + hai.getProcessInstanceId());
            _map.put("taskId", hai.getProcessInstanceId());
//            System.out.println("活动名称：" + hai.getName());
            _map.put("taskName", hai.getName());
//            System.out.println("开始时间：" + DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));
            _map.put("startTime", DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));

//            System.out.println("结束时间：" + hai.getEndTime());
            if (hai.getEndTime() != null) {
                _map.put("endTime", DateUtils.format(hai.getEndTime(), DateUtils.DATE_TIME_PATTERN));
                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSED.getValue());
            } else {

                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSING.getValue());

            }

            //处理意见
            for (Comment cmt : comments) {
                _map.put("description", ((CommentEntity) cmt).getFullMessage());
            }

            //审批意见
            _map.put("aproveAdvice", hai.getDescription());
            taskList.add(_map);
        }

        for (int i = 0; i < list.size(); i++) {
            HistoricTaskInstance hai = list.get(i);
            List<Comment> comments = taskService.getTaskComments(hai.getId());
            Map<String, Object> _map = new LinkedHashMap<String, Object>();
            if (hai.getAssignee() == null || "".equals(hai.getAssignee())) {
                continue;
            }
            _map.put("assignee", hai.getAssignee());
// 			List<User> assiginObjecs = fSysUserAuthService.getUserByIds(Arrays.asList( hai.getAssignee().split(",")));
            StringBuffer inPram = new StringBuffer();
            for (String ss : Arrays.asList(hai.getAssignee().split(","))) {
                inPram.append("'" + ss + "',");
            }
            String inp = inPram.toString().substring(0, inPram.toString().length() - 1);
            String querySql = "select ID_ as userId,FIRST_,LAST_ as username from ACT_ID_USER WHERE ID_ in(" + inp + ")";
            List<Map<String, Object>> assiginObjecs = sqlAdapterMapper.selectSQL(querySql);
            String assigneeName = "";
            Iterator<Map<String, Object>> iterator = assiginObjecs.iterator();

            for (; iterator.hasNext(); ) {
                Map<String, Object> assiginObjec = iterator.next();
                if (iterator.hasNext()) {
                    if (com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(hai.getOwner())) {
                        assigneeName += assiginObjec.get("username") + "(代)" + ",";
                    } else {
                        assigneeName += assiginObjec.get("username") + ",";
                    }
                } else {
                    if (com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(hai.getOwner())) {
                        assigneeName += assiginObjec.get("username") + "(代)";
                    } else {
                        assigneeName += assiginObjec.get("username");
                    }
                }
            }

            if (assiginObjecs != null) {
                _map.put("assigneeName", assigneeName);
            }

//            System.out.println("活动ID:" + hai.getId());
            _map.put("actId", hai.getId());
            _map.put("activityDfId", hai.getTaskDefinitionKey());
//            System.out.println("流程实例ID:" + hai.getProcessInstanceId());
            _map.put("taskId", hai.getProcessInstanceId());
//            System.out.println("活动名称：" + hai.getName());
            _map.put("taskName", hai.getName());
//            System.out.println("开始时间：" + DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));
            _map.put("startTime", DateUtils.format(hai.getStartTime(), DateUtils.DATE_TIME_PATTERN));

//            System.out.println("结束时间：" + hai.getEndTime());
            if (hai.getEndTime() != null) {
                _map.put("endTime", DateUtils.format(hai.getEndTime(), DateUtils.DATE_TIME_PATTERN));
                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSED.getValue());
            } else {

                _map.put("state", WorkflowContants.ProcessRecordState.PROCESSING.getValue());

            }

            //处理意见
            for (Comment cmt : comments) {
                // _map.put("description", ((CommentEntity)cmt).getMessage());
                //解决处理意见超长展示不全问题
                _map.put("description", ((CommentEntity) cmt).getFullMessage());
            }

            //审批意见
            _map.put("aproveAdvice", hai.getDescription());
            taskList.add(_map);
        }

        return taskList;
    }

    @Override
    public PageUtils queryPartakeList(String page, String limit, String dataForm, String userId, String moduleType) {
        int pageq = Integer.parseInt(page != null ? page : "0");
        int limitq = Integer.parseInt(limit != null ? limit : "0");
        Page<Map<String, Object>> p = PageHelper.startPage(pageq, limitq);
        JSONObject obj = com.rf.richfitwheel.common.utils.StringUtils.isBlank(dataForm) ? null : JSONObject.fromObject(dataForm);
        Map<String, Object> pram = new HashMap<String, Object>();
        pram.put("userId", userId);
        if (obj != null) {
            if (obj.containsKey("processName") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("processName"))) {
                pram.put("processName", "%" + obj.getString("processName").trim() + "%");
            }
            //流程状态
            if (obj.containsKey("state") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("state"))) {
                switch (obj.getString("state")) {
                    case "1":
                        pram.put("stateSql", "ins.END_TIME_ IS NULL");
                        break;
                    case "2":
                        pram.put("stateSql", "ins.END_TIME_ IS NOT NULL AND ins.DELETE_REASON_ IS NULL");
                        break;
                    case "3":
                        pram.put("stateSql", "ins.END_TIME_ IS NOT NULL AND ins.DELETE_REASON_ IS NOT NULL");
                        break;
                    default:
                        break;
                }
            }
            if (obj.containsKey("startTime") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("startTime"))) {
                String startTime = obj.getString("startTime");
                Date dateF = null;
                Date dateT = null;
                if (!startTime.startsWith("F") && !startTime.contains("T")) { //非日期范围
                    dateT = DateUtils.setDateTwoThree(new Date());
                    dateF = DateUtils.setDateZero(DateUtils.addDateDays(dateT, -Integer.parseInt(startTime)));
                } else {//日期范围
                    List<Date> dates = DateUtils.fromDateToDate(startTime);
                    dateF = dates.get(0);
                    dateT = dates.get(1);
                }
                pram.put("startDateF", dateF);
                pram.put("startDateT", dateT);
            }
            if (obj.containsKey("endTime") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("endTime"))) {
                String endTime = obj.getString("endTime");
                Date dateF = null;
                Date dateT = null;
                //非日期范围
                if (!endTime.startsWith("F") && !endTime.contains("T")) {
                    dateT = DateUtils.setDateTwoThree(new Date());
                    dateF = DateUtils.setDateZero(DateUtils.addDateDays(dateT, -Integer.parseInt(endTime)));
                } else {//日期范围
                    List<Date> dates = DateUtils.fromDateToDate(endTime);
                    dateF = dates.get(0);
                    dateT = dates.get(1);
                }
                pram.put("endDateF", dateF);
                pram.put("endDateT", dateT);
            }
        }
        List<String> modList = new ArrayList<>(Arrays.asList(moduleType.split(",")));
        if(modList.contains("capitalbudget")){
            modList.add("capitalBudget");
        }
        pram.put("moduleTypes", modList);
        List<Map<String, Object>> list = wfCommonMapper.getParticipantTask(pram);
        PageUtils pageUtils = new PageUtils(p);
        return pageUtils;
    }

    @Override
    public PageUtils queryCreateList(int page, int limit, JSONObject obj, String userId) throws Exception {

        List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();
        HistoricProcessInstanceQuery processInstanceQueryH = historyService.createHistoricProcessInstanceQuery();
        processInstanceQueryH.includeProcessVariables();
        processInstanceQueryH.startedBy(userId);
        if (obj.containsKey("processName") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("processName"))) {
            processInstanceQueryH.processDefinitionNameLike("%" + obj.getString("processName") + "%");
        }
        if (obj.containsKey("briefReport") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("briefReport"))) {
            processInstanceQueryH.processInstanceNameLike("%" + obj.getString("briefReport").trim() + "%");
        }
        //流程状态
        if (obj.containsKey("state") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("state"))) {
            switch (obj.getString(("state"))) {
                case "1":
                    processInstanceQueryH.unfinished();
                    break;
                case "2":
                    processInstanceQueryH.finished();
                    processInstanceQueryH.notDeleted();
                    break;
                case "3":
                    processInstanceQueryH.finished();
                    processInstanceQueryH.deleted();
                    break;
                default:
                    break;
            }
        }
        //开始时间
        if (obj.containsKey("startTime") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("startTime"))) {
            String startTime = obj.getString("startTime");
            Date dateF = null;
            Date dateT = null;
            //非日期范围
            if (!startTime.startsWith("F") && !startTime.contains("T")) {
                dateT = DateUtils.setDateTwoThree(new Date());
                dateF = DateUtils.setDateZero(DateUtils.addDateDays(dateT, -Integer.parseInt(startTime)));
            } else {//日期范围
                List<Date> dates = DateUtils.fromDateToDate(startTime);
                dateF = dates.get(0);
                dateT = dates.get(1);
            }
            processInstanceQueryH.startedAfter(dateF);
            processInstanceQueryH.startedBefore(dateT);
        }
        //结束时间
        if (obj.containsKey("endTime") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("endTime"))) {
            String endTime = obj.getString("endTime");
            Date dateF = null;
            Date dateT = null;
            //非日期范围
            if (!endTime.startsWith("F") && !endTime.contains("T")) {
                dateT = DateUtils.setDateTwoThree(new Date());
                dateF = DateUtils.setDateZero(DateUtils.addDateDays(dateT, -Integer.parseInt(endTime)));
            } else {                                                   //日期范围
                List<Date> dates = DateUtils.fromDateToDate(endTime);
                dateF = dates.get(0);
                dateT = dates.get(1);
            }
            processInstanceQueryH.finishedAfter(dateF);
            processInstanceQueryH.finishedBefore(dateT);
        }
        if(obj.containsKey("moduleType") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("moduleType"))){
            List<String> modList = new ArrayList<>(Arrays.asList(obj.get("moduleType").toString().split(",")));
            if(modList.contains("capitalbudget")){
                modList.add("capitalBudget");
            }
            if(modList.size() > 1){
                processInstanceQueryH.or();
                for(String m : modList){
                    processInstanceQueryH.variableValueEquals("moduleType", m);
                }
                processInstanceQueryH.endOr();
            }else if(modList.size() == 1){
                processInstanceQueryH.variableValueEquals("moduleType", modList.get(0));
            }else{
                //
            }
        }
        processInstanceQueryH.orderByProcessInstanceStartTime().desc();
        List<HistoricProcessInstance> processInstances = processInstanceQueryH.listPage((page - 1) * limit, limit);
        Long count = processInstanceQueryH.count();
        
        /*NativeHistoricProcessInstanceQuery processInstanceQuery = historyService.createNativeHistoricProcessInstanceQuery();
        NativeHistoricProcessInstanceQuery processInstanceCount = historyService.createNativeHistoricProcessInstanceQuery();
        Long count = 0L;
        List<HistoricProcessInstance> processInstances = null;
        //组装 sql
        Map<String, String> sqlMap = assembleSql(obj, processInstanceQuery, processInstanceCount);
        processInstances = processInstanceQuery.sql(sqlMap.get("query")).parameter("userId", userId).listPage((page - 1) * limit, limit);
        count = processInstanceCount.sql(sqlMap.get("count")).parameter("userId", userId).count();*/

        for (HistoricProcessInstance historicProcessInstance : processInstances) {
            //执行实例  如果为空说明流程已结束
            ProcessInstanceQuery processQuery = runtimeService.createProcessInstanceQuery();

            TaskQuery taskQuery = taskService.createTaskQuery().processInstanceId(historicProcessInstance.getId());
//                if (obj.get("tenantId") != null && !"".equals(obj.get("tenantId"))) {
//                    processQuery.processInstanceTenantId(obj.get("tenantId").toString());
//                    taskQuery.taskTenantId(obj.get("tenantId").toString());
//                }

            ExecutionEntity execution = (ExecutionEntity) processQuery.processInstanceId(historicProcessInstance.getId()).singleResult();
            //当前实例的执行到哪个节点
            String activitiId = null;
            String currNode = "";
            //判断流程没结束再去获取当前节点
            if (historicProcessInstance.getEndTime() == null) {
                List<Task> tasks = taskQuery.list();
                List<String> nodeNames = tasks.stream().map(task -> task.getName()).collect(Collectors.toList());
                currNode = StringUtils.join(nodeNames.toArray(), ",");
                activitiId = tasks.isEmpty() ? null : tasks.get(0).getTaskDefinitionKey();
            } else {
                currNode = "已结束";
            }
            ActivityImpl firstUserTask = this.getFirstUserTask(historicProcessInstance.getProcessDefinitionId());
            Map<String, Object> map_ = new LinkedHashMap<String, Object>();
            /*HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery().processInstanceId(historicProcessInstance.getId()).variableName("approveNo").singleResult();
            if (!ObjectUtils.isEmpty(historicVariableInstance)) {
            }*/
            map_.put("approveNo", historicProcessInstance.getProcessVariables().get("approveNo"));
            map_.put("processInstanceId", historicProcessInstance.getId());
            map_.put("processName", historicProcessInstance.getProcessDefinitionName());
            map_.put("description", historicProcessInstance.getName());
            map_.put("nodeName", currNode);
            ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
            ProcessDefinition processDefinition = processDefinitionQuery.processDefinitionId(historicProcessInstance.getProcessDefinitionId()).singleResult();
            map_.put("businessKey", historicProcessInstance.getBusinessKey());
            //详情页面
            map_.put("detailPage", processDefinition.getCategory() == null ? null : processDefinition.getCategory());

            map_.put("actName", historicProcessInstance.getDescription());
            map_.put("startUserId", historicProcessInstance.getStartUserId());
            map_.put("processDefinitionId", historicProcessInstance.getProcessDefinitionId());

            map_.put("startTime", DateUtils.format(historicProcessInstance.getStartTime(), DateUtils.DATE_TIME_PATTERN));
            if (historicProcessInstance.getEndTime() != null) {
                if (historicProcessInstance.getDeleteReason() == null) {
                    map_.put("state", "2");
                } else {
                    map_.put("state", "3");
                }
                map_.put("endTime", DateUtils.format(historicProcessInstance.getEndTime(), DateUtils.DATE_TIME_PATTERN));
            } else {
                map_.put("state", "1");
            }

            //当前节点是否第一个节点
            if (activitiId != null && activitiId.equals(firstUserTask.getId())) {
                //第一个节点
                map_.put("firstUserTask", "1");
            } else {
                map_.put("firstUserTask", "0");
            }

            result.add(map_);
        }

        return new PageUtils(result, count.intValue());
    }


    /**
     * 终止流程
     *
     * @param processInstanceId
     * @param deleteReason
     * @param user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProcess(String processInstanceId, String deleteReason, UserVO user) {
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).finished().singleResult();
        if (historicProcessInstance != null) {
            throw new BusinessException("流程已结束，不能操作！");
        }
        runtimeService.setVariable(processInstanceId, "processInstanceState", WorkflowContants.ProcessInstanceState.TERMINATED.getValue());
        runtimeService.setVariable(processInstanceId, "wf_deleteUserId", user.getId());
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
        Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstanceId).executionId(processInstanceId).singleResult();
        ActivitiEvent event = ActivitiEventBuilder.createEvent(ActivitiEventType.ENTITY_SUSPENDED, execution.getId(), processInstance.getId(), processInstance.getProcessDefinitionId());
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        Map<String, List<String>> taskUsers = new HashMap<>();
        for (Task task : tasks) {
            List<String> resUser = new ArrayList<>();
            if(task.getAssignee() != null){
                resUser.add(task.getAssignee());
            }else{
                List<IdentityLink> listId = taskService.getIdentityLinksForTask(task.getId());
                List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
                resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            }
            taskUsers.put(task.getId(), resUser);
            task.setDescription(WorkflowContants.ProcessResult.TERMINATE.getValue());
            taskService.saveTask(task);
            // 添加删除原因
            taskService.addComment(task.getId(), processInstance.getId(), deleteReason);
            taskService.setAssignee(task.getId(), user.getId());
        }
        runtimeService.deleteProcessInstance(processInstanceId, deleteReason);
        /*for (Task task : tasks) {
            portalTodoSync.todoSyncDelete(task, taskUsers.get(task.getId()), processInstance.getProcessVariables().get("moduleType").toString());
        }*/
        
        runtimeService.dispatchEvent(event);
    }

    /**
     * 终止流程
     *
     * @param businessKey
     * @param deleteReason
     * @param user
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProcessByBusinessKey(String businessKey, String deleteReason, UserVO user) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
        if (processInstance == null) {
            throw new BusinessException("流程不存在！");
        }
        this.deleteProcess(processInstance.getProcessInstanceId(), deleteReason, user);
    }


    /**
     * 发起人撤回,根据业务主键撤回
     *
     * @param businessKey 业务主键
     * @param user        操作用户
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void restartByBusinessKey(String businessKey, UserVO user) {
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessKey).singleResult();
        if (processInstance == null) {
            throw new BusinessException("流程不存在！");
        }
        this.restartByCreater(processInstance.getId(), user);

    }


    /**
     * 查询流程定义对象
     *
     * @param processDefinitionId 流程定义ID
     * @return
     */
    protected ProcessDefinition getProcessDefinition(String processDefinitionId) {
        ProcessDefinition processDefinition = this.repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        return processDefinition;
    }

    /**
     * 获取可退回节点
     *
     * @param taskId
     * @return
     */
    @Override
    public List<Map<String, Object>> getBackTasks(String taskId) {
        List<Map<String, Object>> backTaskList = new LinkedList<>();
        if (StringUtils.isBlank(taskId)) {
            return backTaskList;
        }
        Task nowTask = this.taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) this.repositoryService.getProcessDefinition(nowTask.getProcessDefinitionId());
        ActivityImpl nowActivity = processDefinitionEntity.findActivity(nowTask.getTaskDefinitionKey());
        Set<ActivityImpl> activities = this.findPrevUserTaskActivitys(nowActivity);

        for (ActivityImpl activity : activities) {
            List<HistoricTaskInstance> historicTaskInstances = historyService.createHistoricTaskInstanceQuery().processInstanceId(nowTask.getProcessInstanceId()).taskDefinitionKey(activity.getId()).orderByHistoricTaskInstanceEndTime().desc().list();
            if (historicTaskInstances.size() > 0) {
                HistoricTaskInstance historicTaskInstance = historicTaskInstances.get(0);
                Map<String, Object> _map = new LinkedHashMap<>();
//                System.out.println("活动ID:" + historicTaskInstance.getId());
                _map.put("taskId", historicTaskInstance.getId());
                _map.put("taskDefKey", historicTaskInstance.getTaskDefinitionKey());
//                System.out.println("活动名称：" + historicTaskInstance.getName());
                _map.put("taskName", historicTaskInstance.getName());
//                System.out.println("办理人：" + historicTaskInstance.getAssignee());
                User taskUser = identityService.createUserQuery().userId(historicTaskInstance.getAssignee()).singleResult();
//                Map<String, Object> userMap = (Map<String, Object>) this.fSysUserService.info(historicTaskInstance.getAssignee()).get("user");
                /*_map.put("approveUserAccount", userMap.get("username").toString());
                _map.put("approveUserId", userMap.get("id").toString());
                _map.put("approveUserName", userMap.get("staffName").toString());*/
                _map.put("approveUserAccount", taskUser.getFirstName());
                _map.put("approveUserId", taskUser.getId());
                _map.put("approveUserName", taskUser.getLastName());
                _map.put("approveDate", historicTaskInstance.getStartTime());
                List<Comment> comments = taskService.getTaskComments(historicTaskInstance.getId());
                if (comments.size() > 0) {
                    _map.put("approveMessage", comments.get(0).getFullMessage());
                }
                backTaskList.add(_map);
            }
        }
        return backTaskList;
    }

    /**
     * @param activityImpl      流程节点信息
     * @param activityId        当前流程节点Id信息
     * @param variables         流程变量
     * @param processInstanceId 流程实例ID
     * @return
     * @Description (下一个任务节点信息)
     * @author feizhou
     * @Date 2018年4月13日下午5:40:23
     * @version 1.0.0
     */
    @Override
    public TaskDefinition nextTaskDefinition(ActivityImpl activityImpl, String activityId, Map<String, Object> variables, String processInstanceId) {

        PvmActivity ac = null;

        // 如果遍历节点为用户任务并且节点不是当前节点信息
        if ("userTask".equals(activityImpl.getProperty("type")) && !activityId.equals(activityImpl.getId())) {
            // 获取该节点下一个节点信息
            TaskDefinition taskDefinition = ((UserTaskActivityBehavior) activityImpl.getActivityBehavior())
                    .getTaskDefinition();
            return taskDefinition;

        } else if (!"endEvent".equals(activityImpl.getProperty("type"))) {
            // 当前节点是不结束节点的情况

            // 获取节点所有流向线路信息
            List<PvmTransition> outTransitions = activityImpl.getOutgoingTransitions();
            List<PvmTransition> outTransitionsTemp = null;
            for (PvmTransition tr : outTransitions) {
                // 这里遍历的当然节点所有流程线的的终点节点
                ac = tr.getDestination(); // 获取线路的终点节点
                // 如果流向线路为排他网关
                if ("exclusiveGateway".equals(ac.getProperty("type"))) {
                    outTransitionsTemp = ac.getOutgoingTransitions();

                    // 如果排他网关只有一条线路信息
                    if (outTransitionsTemp.size() == 1) {
                        return nextTaskDefinition((ActivityImpl) outTransitionsTemp.get(0).getDestination(), activityId,
                                variables, processInstanceId);
                    } else if (outTransitionsTemp.size() > 1) { // 如果排他网关有多条线路信息

                        ActivityImpl nextActivityImpl = getNextActivityImplByLineCondition(outTransitionsTemp,
                                variables);
                        return nextTaskDefinition(nextActivityImpl, activityId, variables, processInstanceId);

                    }
                } else if ("userTask".equals(ac.getProperty("type"))) {// 下一个节点是用户任务
                    Boolean currenLineConditionResule = getCurrenLineConditionResule(tr, variables);
                    if (currenLineConditionResule) {
                        return ((UserTaskActivityBehavior) ((ActivityImpl) ac).getActivityBehavior())
                                .getTaskDefinition();
                    }
                }

            }
        }
        return null;
    }

    /**
     * @param outTransition
     * @param variables
     * @return
     * @Description (判断当前流程线是否满足流程参数条件)
     * @author feizhou
     * @Date 2018年4月13日下午6:32:16
     * @version 1.0.0
     */
    public Boolean getCurrenLineConditionResule(PvmTransition outTransition, Map<String, Object> variables) {

        boolean stringtoBoolean = true;
        Object conStr = outTransition.getProperty("conditionText"); // 获取线路判断条件信息
        // s: ${money>1000 or price >12}
        // variables (money=1100)
        // variables (price=100)
        // 去掉${和}
        String ElStr = "";
        if (conStr != null) {// 有条件
            ElStr = String.valueOf(conStr);
            ElStr = ElStr.substring(2, ElStr.length() - 1);
            try {
                stringtoBoolean = stringToBoolean(ElStr, variables);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            return stringtoBoolean;
        } else {// 没有条件
            return stringtoBoolean;
        }
    }

    /**
     * @param outTransitionsTemp
     * @param variables
     * @return
     * @Description (如果是排他网关判断, 获取排他网关对应的用户任务节点)
     * @author feizhou
     * @Date 2018年4月13日下午4:41:55
     * @version 1.0.0
     */
    public ActivityImpl getNextActivityImplByLineCondition(List<PvmTransition> outTransitionsTemp,
                                                           Map<String, Object> variables) {

        for (PvmTransition tr1 : outTransitionsTemp) {
            Object conStr = tr1.getProperty("conditionText"); // 获取线路判断条件信息
            // s: ${money>1000 or price >12}
            // variables (money=1100)
            // variables (price=100)
            // 去掉${和}
            String ElStr = "";
            if (conStr != null) {// 有条件
                ElStr = String.valueOf(conStr);
                ElStr = ElStr.substring(2, ElStr.length() - 1);
                try {
                    boolean stringtoBoolean = stringToBoolean(ElStr, variables);
                    if (stringtoBoolean) {
                        return (ActivityImpl) tr1.getDestination();
                    }
                } catch (ScriptException e) {
                    continue;
                }
            } else {// 没有条件
                return (ActivityImpl) tr1.getDestination();
            }
        }
        return null;
    }

    /**
     * @param str
     * @param var
     * @return
     * @throws ScriptException
     * @Description (字符串表达式计算逻辑值)
     * @author feizhou
     * @Date 2018年4月13日下午2:30:28
     * @version 1.0.0
     */
    public static boolean stringToBoolean(String str, Map<String, Object> var) throws ScriptException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        Set<String> keys = var.keySet();
        for (String key : keys) {
            engine.put(key, var.get(key));
        }
        str = str.replaceAll(" or ", " || ").replaceAll(" and ", " && ");
        Object result = engine.eval(str);
        return Boolean.parseBoolean(String.valueOf(result));

    }

    public static void main(String[] args){
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        engine.put("flag1", 0);
        engine.put("flag2", 0);
        engine.put("flag3", 0);
        engine.put("flag4", 0);
        engine.put("flag5", 0);
//        engine.put("periodType", "01");
//        engine.put("controlLine", 60);
        String str = "flag1==0 && flag2==0 && flag3==0 && flag4==0 && flag5==0";
        try {
            Object result = engine.eval(str);
            System.out.println(Boolean.parseBoolean(String.valueOf(result)));
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
    /**
     * 我创建的流程-sql组装
     *
     * @param obj
     * @param processInstanceQuery
     * @param processInstanceCount
     */
    private Map<String, String> assembleSql(JSONObject obj, NativeHistoricProcessInstanceQuery processInstanceQuery, NativeHistoricProcessInstanceQuery processInstanceCount) {
        String[] tenantIds = com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("tenantIds")) ? obj.get("tenantIds").toString().split(",") : null;

        String query_sql = "SELECT DISTINCT RES.ID_,RES.PROC_INST_ID_,RES.BUSINESS_KEY_,RES.PROC_DEF_ID_,RES.START_TIME_,RES.END_TIME_,RES.DURATION_,RES.START_USER_ID_,RES.START_ACT_ID_,RES.END_ACT_ID_,RES.SUPER_PROCESS_INSTANCE_ID_,RES.DELETE_REASON_,RES.TENANT_ID_,RES.NAME_, DEF.KEY_ AS PROC_DEF_KEY_, DEF.NAME_ AS PROC_DEF_NAME_,DEF.VERSION_ AS PROC_DEF_VERSION_,DEF.DEPLOYMENT_ID_ AS DEPLOYMENT_ID_ " +
                "FROM ACT_HI_PROCINST RES LEFT OUTER JOIN ACT_RE_PROCDEF DEF ON RES.PROC_DEF_ID_ = DEF.ID_ " +
                " LEFT OUTER JOIN ACT_HI_VARINST_ROW AS VAR ON RES.PROC_INST_ID_=var.PROC_INST_ID_" +
                " WHERE RES.START_USER_ID_ = #{userId} ";
        String count_sql = "SELECT  COUNT(DISTINCT RES.ID_) " +
                "FROM ACT_HI_PROCINST RES LEFT OUTER JOIN ACT_RE_PROCDEF DEF ON RES.PROC_DEF_ID_ = DEF.ID_ " +
                " LEFT OUTER JOIN ACT_HI_VARINST_ROW AS VAR ON RES.PROC_INST_ID_=var.PROC_INST_ID_" +
                " WHERE RES.START_USER_ID_ = #{userId} ";
        String order_sql = " ORDER BY RES.START_TIME_ DESC";
//        if (tenantIds != null) {
//            String base_or_sql = "AND (RES.TENANT_ID_ LIKE CONCAT('%', #{tenantId0}, '%') ";
//            for (int i = 0; i < tenantIds.length; i++) { // 多个租户ID处理
//                if (i == 0) {
//                    processInstanceQuery.parameter("tenantId0", tenantIds[i]);
//                    processInstanceCount.parameter("tenantId0", tenantIds[i]);
//                    continue;
//                }
//                base_or_sql = base_or_sql.concat("OR RES.TENANT_ID_ LIKE CONCAT('%', #{tenantId" + i + "}, '%')");
//                processInstanceQuery.parameter("tenantId" + i, tenantIds[i]);
//                processInstanceCount.parameter("tenantId" + i, tenantIds[i]);
//            }
//            base_or_sql = base_or_sql.concat(") ");
//            query_sql = query_sql.concat(base_or_sql);
//            count_sql = count_sql.concat(base_or_sql);
//        }
        if(obj.containsKey("moduleType") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("moduleType"))){
            query_sql = query_sql.concat(" AND UPPER(var.MODULETYPE) in ('" + obj.getString("moduleType").replaceAll(",","','").toUpperCase() + "') ");
            count_sql = count_sql.concat(" AND UPPER(var.MODULETYPE) in ('" + obj.getString("moduleType").replaceAll(",","','").toUpperCase() + "') ");
//            processInstanceQuery.parameter("moduleType", "'" + obj.getString("moduleType").replaceAll(",","','") + "'");
//            processInstanceCount.parameter("moduleType", "'" + obj.getString("moduleType").replaceAll(",","','")+ "'");
        }
        //查询条件
        if (obj.containsKey("processName") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("processName"))) {
            /*String[] processNames = obj.getString("processName").split(",");
            String in_sql = "";
            for (int i = 0; i < processNames.length; i++) {
                in_sql = in_sql.concat("#{processName" + i + "}");
                processInstanceQuery.parameter("processName" + i, processNames[i]);
                processInstanceCount.parameter("processName" + i, processNames[i]);

                if (i < processNames.length - 1) {
                    in_sql = in_sql.concat(",");
                }
            }*/
            query_sql = query_sql.concat("AND DEF.NAME_ like #{processName} ");
            count_sql = count_sql.concat("AND DEF.NAME_ like #{processName} ");
            processInstanceQuery.parameter("processName", "%" + obj.getString("processName") + "%");
            processInstanceCount.parameter("processName", "%" + obj.getString("processName") + "%");
        }
        //摘要
        if (obj.containsKey("briefReport") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.get("briefReport"))) {
            query_sql = query_sql.concat("AND RES.NAME_ like #{briefReport} ");
            count_sql = count_sql.concat("AND RES.NAME_ like #{briefReport} ");
            processInstanceQuery.parameter("briefReport", "%" + obj.getString("briefReport").trim() + "%");
            processInstanceCount.parameter("briefReport", "%" + obj.getString("briefReport").trim() + "%");
        }
        //流程状态
        if (obj.containsKey("state") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("state"))) {
            switch (obj.getString(("state"))) {
                case "1":
                    query_sql = query_sql.concat(" AND RES.END_TIME_ IS NULL");
                    count_sql = count_sql.concat(" AND RES.END_TIME_ IS NULL");
                    break;
                case "2":
                    query_sql = query_sql.concat(" AND RES.END_TIME_ IS NOT NULL AND RES.DELETE_REASON_ IS NULL ");
                    count_sql = count_sql.concat(" AND RES.END_TIME_ IS NOT NULL AND RES.DELETE_REASON_ IS NULL ");
                    break;
                case "3":
                    query_sql = query_sql.concat(" AND RES.END_TIME_ IS NOT NULL AND RES.DELETE_REASON_ IS NOT NULL ");
                    count_sql = count_sql.concat(" AND RES.END_TIME_ IS NOT NULL AND RES.DELETE_REASON_ IS NOT NULL ");
                default:
                    break;
            }
        }
        //开始时间
        if (obj.containsKey("startTime") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("startTime"))) {
            String startTime = obj.getString("startTime");
            Date dateF = null;
            Date dateT = null;
            //非日期范围
            if (!startTime.startsWith("F") && !startTime.contains("T")) {
                dateT = DateUtils.setDateTwoThree(new Date());
                dateF = DateUtils.setDateZero(DateUtils.addDateDays(dateT, -Integer.parseInt(startTime)));
            } else {//日期范围
                List<Date> dates = DateUtils.fromDateToDate(startTime);
                dateF = dates.get(0);
                dateT = dates.get(1);
            }
            query_sql = query_sql.concat(" AND RES.START_TIME_ BETWEEN #{startDateF} AND #{startDateT}");
            count_sql = count_sql.concat(" AND RES.START_TIME_ BETWEEN #{startDateF} AND #{startDateT}");
            processInstanceQuery.parameter("startDateF", dateF);
            processInstanceQuery.parameter("startDateT", dateT);
            processInstanceCount.parameter("startDateF", dateF);
            processInstanceCount.parameter("startDateT", dateT);
        }
        //结束时间
        if (obj.containsKey("endTime") && com.rf.richfitwheel.common.utils.StringUtils.isNotBlank(obj.getString("endTime"))) {
            String endTime = obj.getString("endTime");
            Date dateF = null;
            Date dateT = null;
            //非日期范围
            if (!endTime.startsWith("F") && !endTime.contains("T")) {
                dateT = DateUtils.setDateTwoThree(new Date());
                dateF = DateUtils.setDateZero(DateUtils.addDateDays(dateT, -Integer.parseInt(endTime)));
            } else {                                                   //日期范围
                List<Date> dates = DateUtils.fromDateToDate(endTime);
                dateF = dates.get(0);
                dateT = dates.get(1);
            }
            query_sql = query_sql.concat(" AND RES.END_TIME_ BETWEEN #{endDateF} AND #{endDateT}");
            count_sql = count_sql.concat(" AND RES.END_TIME_ BETWEEN #{endDateF} AND #{endDateT}");
            processInstanceQuery.parameter("endDateF", dateF);
            processInstanceQuery.parameter("endDateT", dateT);
            processInstanceCount.parameter("endDateF", dateF);
            processInstanceCount.parameter("endDateT", dateT);
        }
        query_sql = query_sql.concat(order_sql);
        Map<String, String> queryMap = new HashMap<>(2);
        queryMap.put("query", query_sql);
        queryMap.put("count", count_sql);
        return queryMap;
    }

    /**
     * 获取进程 processDefinitionKey 的第一个节点定义
     *
     * @param processDefinitionId
     * @return
     * @throws Exception
     */
    @Override
    public ActivityImpl getFirstUserTask(String processDefinitionId) {
        ProcessDefinition processdefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();
        return this.getFirstUserTask(processdefinition);
    }

    @Override
    public ActivityImpl getFirstUserTask(ProcessDefinition processdefinition) {
        ActivityImpl activityImpl = null;
        if (processdefinition != null) {
            BpmnModel model = repositoryService.getBpmnModel(processdefinition.getId());
            ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl) repositoryService)
                    .getDeployedProcessDefinition(processdefinition.getId());
            if (model != null) {
                // 获取所有节点
                Collection<FlowElement> flowElements = model.getMainProcess().getFlowElements();
                for (FlowElement e : flowElements) {
                    if (e instanceof StartEvent) {
                        StartEvent startEvent = (StartEvent) e;
                        ActivityImpl startEventActivityImpl = processDefinitionEntity.findActivity(startEvent.getId());// 当前节点
                        List<PvmTransition> outTransitions = startEventActivityImpl.getOutgoingTransitions();
                        for (PvmTransition tr : outTransitions) {
                            PvmActivity ac = tr.getDestination(); // 获取线路的终点节点
                            if ("userTask".equals(ac.getProperty("type"))) {
                                activityImpl = processDefinitionEntity.findActivity(ac.getId());// 当前节点
                                break;
                            } else if ("manualTask".equals(ac.getProperty("type"))) {
                                List<PvmTransition> outTransitionsManual = startEventActivityImpl.getOutgoingTransitions();
                                for (PvmTransition trManual : outTransitionsManual) {
                                    PvmActivity acManual = trManual.getDestination(); // 获取线路的终点节点
                                    if ("userTask".equals(acManual.getProperty("type"))) {
                                        activityImpl = processDefinitionEntity.findActivity(ac.getId());// 当前节点
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
        }
        return activityImpl;
    }

    @Override
    public List<WfAuthRule> findAuthRuleByTask(Task task) {
        WfProcessTask wfProcessTask = this.wfProcessTaskService.findByProDefIdAndTaskDefKey(task.getProcessDefinitionId(), task.getTaskDefinitionKey());
        if (ObjectUtils.isEmpty(wfProcessTask)) {
            return new ArrayList<>();
        }
        List<WfAuthRule> authRules = this.wfAuthRuleService.listByStationProcessOrderId(wfProcessTask.getStationProcessOrderId());
        return authRules;
    }

    @Override
    public WfAuthRule validAuthRules(Task task, Map<String, Object> variables) throws ScriptException {
        List<WfAuthRule> authRules = this.findAuthRuleByTask(task);
        for (WfAuthRule authRule : authRules) {
            if (authRule.getRuleType().equals("1")) {
                if (this.validAuthRule1(authRule, variables)) {//只要有一个规则满足条件就返回授权规则,验证属性
                    return authRule;
                }
            } else {
                if (this.validAuthRule2(authRule, variables)) {//只要有一个规则满足条件就返回授权规则,验证表达式
                    return authRule;
                }
            }
        }
        return null;
    }

    @Override
    public void dealWithNextTask(String processInstanceId, Map<String, Object> variables, String approveUserId) throws ScriptException{
        List<Task> tasks = this.taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        if(StringUtils.isNotBlank(approveUserId)){
            //如果指定了审批人则用审批人检出
            for(Task task : tasks){
                taskService.claim(task.getId(), approveUserId);
            }
        }
        //重新查一下最新的
        tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        /*//发给门户新的待办
        //还有下一个节点的情况
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
        List<TaskPortalTodoSync> taskListNew;
        taskListNew = tasks.stream().map(m -> {
            TaskPortalTodoSync taskPortalTodoSync = new TaskPortalTodoSync();
            taskPortalTodoSync.setTask(m);
            List<String> resUser = new ArrayList<>();
            if(m.getAssignee() != null){
                resUser.add(m.getAssignee());
            }else{
                List<IdentityLink> listId = taskService.getIdentityLinksForTask(m.getId());
                List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
                resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            }
            taskPortalTodoSync.setReceiveUsers(resUser);
            return taskPortalTodoSync;
        }).collect(Collectors.toList());
        if(instance != null){
            UserVO user = UserUtil.getUser();
            if (null == user) {
                user = UserUtil.getUser(variables.get("userSessionId").toString());
            }
            portalTodoSync.todoSync(instance, (String) instance.getProcessVariables().get("moduleType"), user.getId(), taskListNew);
        }*/
        for (Task task : tasks) {
            Set<User> users = new HashSet<>();
            if(task.getAssignee() != null){
                users.add(getUser(task.getAssignee()));
            }else{
                try{
                    users = this.getTaskCandidate(task.getId());//获取当前任务对应的审批人
                }catch(Exception e){
                    log.error("没有获取到流程任务的审批人", e);
                }
            }
            if(users.isEmpty())
                throw new BusinessException("节点没有配置审批人");
            //只有指定了审批人且是自己的情况下才自动审批通过
            //下以节点不自动审批通过2023-11-02
            /*if (task.getAssignee() != null && task.getAssignee().equals(UserUtil.getUser().getId())) {
                ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) this.repositoryService.getProcessDefinition(task.getProcessDefinitionId());
                ActivityImpl nowActivity = processDefinitionEntity.findActivity(task.getTaskDefinitionKey());
                Set<ActivityImpl> activities = this.findPrevUserTaskActivitys(nowActivity);//根据流程图往前找结点
                Iterator<ActivityImpl> iter = activities.iterator();
                boolean hasApprove = false;//有审批记录
                while (iter.hasNext()) {
                    ActivityImpl activity = iter.next();
                    List<HistoricTaskInstance> historicTaskInstances = this.historyService.createHistoricTaskInstanceQuery().taskDefinitionKey(activity.getId()).taskAssignee(task.getAssignee()).processInstanceId(processInstanceId).list();
                    if (historicTaskInstances.size() > 0) {
                        task = taskService.createTaskQuery().taskId(task.getId()).singleResult();
                        Map<String, Object> hisVariables = historyService.createHistoricProcessInstanceQuery().includeProcessVariables().processInstanceId(task.getProcessInstanceId()).singleResult().getProcessVariables();
                        hisVariables.putAll(variables);
                        WfAuthRule wfAuthRule = validAuthRules(task, hisVariables);//验证授权规则
                        if (ObjectUtils.isEmpty(wfAuthRule)) {
                            taskService.addComment(task.getId(), task.getProcessInstanceId(), "同审批人自动通过");
                            //没有授权规则
                            this.recordTransfer(task, variables);
                            taskService.complete(task.getId(), variables);//完成任务
                        } else {
                            if (wfAuthRule.getToStationId().equals("end")) {
                                //授权规则跳转到结束则授权流程结束,结束之前先判断后续节点有没有授权规则，如果后续节点有不满足的授权规则的话就不能跳转到结束
                                //上级设置了无条件参与的情况下也不允许结束
                                if(checkAllWfAuthRuleFollow(task, variables)){
                                    taskService.addComment(task.getId(), task.getProcessInstanceId(), "同审批人自动通过");
                                    //后面还有授权规则，不允许结束，执行下一个节点
                                    recordTransfer(task, variables);
                                    taskService.complete(task.getId(), variables);//完成任务
                                }else{
                                    ActivitiEvent event = ActivitiEventBuilder.createEvent(ActivitiEventType.ENTITY_SUSPENDED, task.getExecutionId(), task.getProcessInstanceId(), task.getProcessDefinitionId());
                                    runtimeService.deleteProcessInstance(task.getProcessInstanceId(), null);//流程结束
                                    runtimeService.dispatchEvent(event);
                                }
                            }else {
                                //找到授权规则跳转节点
                                WfProcessTask wfProcessTask = wfProcessTaskService.getByStationProcessOrderId(wfAuthRule.getToStationId());
                                if (ObjectUtils.isEmpty(wfProcessTask)) {//没找到授权规则跳转节点正常提交
                                    taskService.addComment(task.getId(), task.getProcessInstanceId(), "同审批人自动通过");
                                    recordTransfer(task, variables);
                                    taskService.complete(task.getId(), variables);//完成任务
                                } else {
                                    //找到就跨级跳转
                                    doJump(task, wfProcessTask.getTaskDefKey(), "同审批人自动通过", variables);
                                }
                            }
                        }
                        List<String> listUsers = new ArrayList<>();
                        listUsers.add(task.getAssignee());
                        portalTodoSync.todoSyncDone(task, listUsers, (String) instance.getProcessVariables().get("moduleType"));
                        hasApprove = true;
                        break;
                    }
                }
                if (hasApprove) {
                    break;
                }
            }*/

        }
    }
    public void dealWithNextTaskForMq(String processInstanceId, Map<String, Object> variables, String approveUserId, UserVO user) throws ScriptException{
        List<Task> tasks = this.taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        if(StringUtils.isNotBlank(approveUserId)){
            //如果指定了审批人则用审批人检出
            for(Task task : tasks){
                taskService.claim(task.getId(), approveUserId);
            }
        }
        //重新查一下最新的
        tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        /*//发给门户新的待办
        //还有下一个节点的情况
        ProcessInstance instance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).includeProcessVariables().singleResult();
        List<TaskPortalTodoSync> taskListNew;
        taskListNew = tasks.stream().map(m -> {
            TaskPortalTodoSync taskPortalTodoSync = new TaskPortalTodoSync();
            taskPortalTodoSync.setTask(m);
            List<String> resUser = new ArrayList<>();
            if(m.getAssignee() != null){
                resUser.add(m.getAssignee());
            }else{
                List<IdentityLink> listId = taskService.getIdentityLinksForTask(m.getId());
                List<String> uGroup = listId.stream().filter(f -> f.getType().equals("candidate")).map(IdentityLink::getGroupId).collect(Collectors.toList());
                resUser = fSysUserService.getUserListByStationIds(String.join(",", uGroup)).stream().map(com.rf.richfitwheel.admin.sys.model.User::getId).collect(Collectors.toList());
            }
            taskPortalTodoSync.setReceiveUsers(resUser);
            return taskPortalTodoSync;
        }).collect(Collectors.toList());
        if(instance != null){
            portalTodoSync.todoSync(instance, (String) instance.getProcessVariables().get("moduleType"), user.getId(), taskListNew);
        }*/
        for (Task task : tasks) {
            Set<User> users = new HashSet<>();
            if(task.getAssignee() != null){
                users.add(getUser(task.getAssignee()));
            }else{
                try{
                    users = this.getTaskCandidate(task.getId());//获取当前任务对应的审批人
                }catch(Exception e){
                    log.error("没有获取到流程任务的审批人", e);
                }
            }
            if(users.isEmpty())
                throw new BusinessException("节点没有配置审批人");
        }
    }

    /**
     * 判断该节点后续是否还有授权规则
     *
     * @param task      当前节点任务
     * @param variables 参数
     * @return true代表还有授权规则，不能结束；false代表可以结束
     */
    @Override
    public boolean checkAllWfAuthRuleFollow(Task task, Map<String, Object> variables) throws ScriptException{
        try{
            WfProcessTask wfProcessTask = this.wfProcessTaskService.findByProDefIdAndTaskDefKey(task.getProcessDefinitionId(), task.getTaskDefinitionKey());
            WfStationProcessOrder order = wfStationProcessOrderMapper.selectByPrimaryKey(wfProcessTask.getStationProcessOrderId());
            /*if(parentUncondtionnal(order.getStationProcessId())){
                return true;
            }*/
            WfStationProcessOrderExample example = new WfStationProcessOrderExample();
            WfStationProcessOrderExample.Criteria criteria = example.createCriteria();
            criteria.andStationProcessIdEqualTo(order.getStationProcessId());
            criteria.andApproveOrderGreaterThan(order.getApproveOrder());
            //只需要判断上级对下级设置的规则，即每一级最后一个节点
            criteria.andLastStationEqualTo(Constant.COMMON_YES_OR_NO_YES);
            WfStationProcessOrderExample.Criteria criteriaL = example.createCriteria();
            criteriaL.andStationProcessIdEqualTo(order.getStationProcessId());
            criteriaL.andApproveOrderGreaterThan(order.getApproveOrder());
            //兼容历史数据，新加字段没值的按照需要校验处理
            criteriaL.andLastStationIsNull();
            example.or(criteriaL);
            List<WfStationProcessOrder> list = wfStationProcessOrderMapper.selectByExample(example);
            if(!list.isEmpty()){
                WfAuthRuleExample example1 = new WfAuthRuleExample();
                WfAuthRuleExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andStationProcessOrderIdIn(list.stream().map(WfStationProcessOrder::getId).collect(Collectors.toList()));
                List<WfAuthRule> authRules = wfAuthRuleMapper.selectByExample(example1);
                for (WfAuthRule authRule : authRules) {
                    if (authRule.getRuleType().equals("1")) {
                        if (!this.validAuthRule1(authRule, variables)) {
                            //只要有一个规则不满足条件就证明不能结束
                            return true;
                        }
                    } else {
                        if (!this.validAuthRule2(authRule, variables)) {
                            //只要有一个规则不满足条件就证明不能结束
                            return true;
                        }
                    }
                }
            }
            return false;
        }catch(Exception e){
            log.error(e.getMessage(), e);
           return false;
        }
    }
    
    /**
     * 上级有无条件参与的情况下不允许结束
     * @param stationProcessId 当前流程
     * @return 是否不可结束
     */
    private boolean parentUncondtionnal(String stationProcessId){
        WfStationProcess sp = wfStationProcessMapper.selectByPrimaryKey(stationProcessId);
        OrgVO org = sysOrgFeignService.getOrgVOObjectByOrgCode(sp.getOrgCode());
        if(org != null && org.getParentOrg() != null){
            WfStationProcessExample example = new WfStationProcessExample();
            WfStationProcessExample.Criteria criteria = example.createCriteria();
            criteria.andOrgCodeEqualTo(org.getParentOrg().getOrgCode());
            criteria.andFolderCodeEqualTo(sp.getFolderCode());
            List<WfStationProcess> list = wfStationProcessMapper.selectByExample(example);
            if(!list.isEmpty()){
                //查询是否有单独为该机构配置的的无条件参与配置
                WfStationProcessParPubExample example1 = new WfStationProcessParPubExample();
                WfStationProcessParPubExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andStationProcessIdEqualTo(list.get(0).getId());
                criteria1.andOrgIdEqualTo(org.getId());
                List<WfStationProcessParPub> list1 = wfStationProcessParPubMapper.selectByExample(example1);
                boolean hasUp = false;
                for(WfStationProcessParPub parPub : list1){
                    if(StationProcessContant.ParSubType.UNCONDTIONNAL.getValue().equals(parPub.getParSub())){
                        return true;
                    }
                    if(StationProcessContant.ParSubType.CONDITIONAL.getValue().equals(parPub.getParSub())){
                        hasUp = true;
                    }
                }
                //没有单独配置的情况下再看统一配置
                if(list1.isEmpty() && StationProcessContant.ParSubType.UNCONDTIONNAL.getValue().equals(list.get(0).getParSub())){
                    //上级如果是无条件参与则返回true
                    return true;
                }
                if(!hasUp && StationProcessContant.ParSubType.CONDITIONAL.getValue().equals(list.get(0).getParSub())){
                    //上级没设置为有条件参与的
                    hasUp = true;
                }
                if(hasUp){
                    return parentUncondtionnal(list.get(0).getId());
                }
            }
        }
        return false;
    }
    
    private Set<User> getTaskCandidate(String taskId) {
        Set<User> users = new HashSet<>();
        List identityLinkList = taskService.getIdentityLinksForTask(taskId);
        if (identityLinkList != null && identityLinkList.size() > 0) {
            for (Iterator iterator = identityLinkList.iterator(); iterator.hasNext(); ) {
                IdentityLink identityLink = (IdentityLink) iterator.next();
                if (identityLink.getUserId() != null) {
                    User user = getUser(identityLink.getUserId());
                    if (user != null) {
                        users.add(user);
                    }
                }
                if (identityLink.getGroupId() != null) {
                    // 根据组获得对应人员
                    List userList = identityService.createUserQuery().memberOfGroup(identityLink.getGroupId()).list();
                    if (userList != null && userList.size() > 0) {
                        users.addAll(userList);
                    }

                }
            }

        }
        return users;
    }

    private User getUser(String userId) {
        User user = identityService.createUserQuery().userId(userId).singleResult();
        return user;
    }

    public boolean validAuthRule1(WfAuthRule authRule, Map<String, Object> variables) {
        String ruleValue = "";
        if (variables.containsKey(authRule.getRuleField())) {
            ruleValue = variables.get(authRule.getRuleField()).toString();
        }
        if (StringUtils.isBlank(ruleValue)) {
            return false;
        } else {
            BigDecimal bigDecimal = new BigDecimal(ruleValue);
            if ("=".equals(authRule.getRuleCondition())) {//等于
                if (bigDecimal.compareTo(authRule.getRuleAmt()) == 0) {
                    return true;
                }
            } else if (">".equals(authRule.getRuleCondition())) {//大于
                if (bigDecimal.compareTo(authRule.getRuleAmt()) == 1) {
                    return true;
                }
            } else if (">=".equals(authRule.getRuleCondition())) {//大于等于
                if (bigDecimal.compareTo(authRule.getRuleAmt()) != -1) {
                    return true;
                }
            } else if ("<".equals(authRule.getRuleCondition())) {//小于
                if (bigDecimal.compareTo(authRule.getRuleAmt()) == -1) {
                    return true;
                }
            } else if ("<=".equals(authRule.getRuleCondition())) {//小于等于
                if (bigDecimal.compareTo(authRule.getRuleAmt()) != 1) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean validAuthRule2(WfAuthRule authRule, Map<String, Object> variables) throws ScriptException {
        return stringToBoolean(authRule.getRuleCondition(), variables);
    }
}
